package cn.edu.jmu.oelp.controller;

import cn.edu.jmu.oelp.pojo.Entity;
import cn.edu.jmu.oelp.pojo.EntityRelation;
import cn.edu.jmu.oelp.service.EntityRelationNeo4jService;
import cn.edu.jmu.oelp.service.EntityService;
import cn.edu.jmu.oelp.service.EntityNeo4jService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;

@RestController
@Transactional(rollbackFor=Exception.class)
public class Neo4jController {
    @Autowired
    private EntityService entityService;
    @Autowired
    private EntityNeo4jService entityNeo4jService;
    @Autowired
    private EntityRelationNeo4jService relationNeo4jService;

    @RequestMapping("/getEntity")
    public List<Entity> getEntity(){
        return entityNeo4jService.findAll();
    }

    @RequestMapping("/getEntityByArticleId")
    public List<Entity> getEntityByArticleId(int articleId){
        return entityNeo4jService.findByArticleId(articleId);
    }

    @RequestMapping("/getEntityByArticleIdAndParagraphsId")
    public List<Entity> getEntityByArticleId(int articleId, int paragraphsId){
        return entityNeo4jService.findByArticleIdAndParagraphsId(articleId, paragraphsId);
    }

    @RequestMapping("/getParaEntityByUserId")
    public List<Entity> getParaEntityByUserId(int articleId, int paragraphsId, int userId){
        int paraId = paragraphsId;
        if(paragraphsId == 0)
        {
            paraId = entityService.lastParagraphsId(userId);
        }
        return entityNeo4jService.findByArticleIdAndParagraphsIdAndUserId(articleId, paraId, userId);
    }

    @RequestMapping("/getRelation")
    public List<EntityRelation> getRelation()
    {
        return relationNeo4jService.findAll();
    }

    @RequestMapping("/getRelationByArticleId")
    public List<EntityRelation> getRelationByArticleId(int articleId)
    {
        List<EntityRelation> relationList = relationNeo4jService.findAll();

        Iterator<EntityRelation> relationIterator = relationList.iterator();
        while(relationIterator.hasNext())
        {
            EntityRelation relation = relationIterator.next();
            Entity startEntity = relation.getStartEntity();
            Entity endEntity = relation.getEndEntity();
            if(startEntity.getArticleId() != articleId || endEntity.getArticleId() != articleId)
            {
                relationIterator.remove();
            }
        }
        //jdk1.8移除等于11的元素
        // list.removeIf(item -> "11".equals(item));
        return relationList;
    }

}
